package com.xaicode.learn.netty.codec2;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author Locker xaicode@sina.com
 * @version 1.0
 * @date 2021/6/13 0013 23:29
 */
@Slf4j
public class NettyServerHandlerWithSimpleChannel extends SimpleChannelInboundHandler<Codec2Proto.All> {

    // read client msg
    @Override
    public void channelRead0(ChannelHandlerContext ctx, Codec2Proto.All receive) throws Exception {

        // read client
        Codec2Proto.All.DateType dataType = receive.getDataType();
        if (dataType.equals(Codec2Proto.All.DateType.StudentType)) {
            Codec2Proto.Student student = receive.getStudent();
            log.info("receive client Student id={}, name={}", student.getId(), student.getName());
        } else if (dataType.equals(Codec2Proto.All.DateType.WorkerType)) {
            Codec2Proto.Worker worker = receive.getWorker();
            log.info("receive client Worker name={}, age={}", worker.getName(), worker.getAge());
        } else {
            log.error("wrong transfer type");
        }

    }

    // read client msg complete
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {

        log.info("read client msg complete");

        // write and flush
        ctx.writeAndFlush(Unpooled.copiedBuffer("server complete: hello client", CharsetUtil.UTF_8));
    }

    // on exception
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
